//
//  RecommendMainViewController.m
//  HappyTrip
//
//  Created by yuxuesong on 15-3-22.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "RecommendMainViewController.h"
#import "TravelNoteViewController.h"
#import "UIImageView+AFNetworking.h"
#import "ScrollViewCell.h"
#import "HotCell.h"
#import "FineCell.h"
#import "TopicCell.h"
#import "LineCell.h"
#import "TopicWebViewController.h"
#import "TrendQueueViewController.h"
#import "NiceQueueViewController.h"
// 轮翻图片
#import "SDCycleScrollView.h"
// 菊花
#import "MBProgressHUD.h"
// 数据库
#import "DateBaseHandler.h"
//第二个tabBar
#import "DestinationMainViewController.h"
// 刷新
#import "MJRefresh.h"


@interface RecommendMainViewController ()<UITableViewDataSource
, UITableViewDelegate, SDCycleScrollViewDelegate>

@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) UIScrollView *scrollView;
@property (nonatomic, retain) NSMutableArray *elements;
@property (nonatomic, retain) NSMutableArray *hotArr;
@property (nonatomic, retain) NSArray *dataArr;
@property (nonatomic, retain) UIAlertView *alertView;
@property (nonatomic, retain) SDCycleScrollView *cycleScrollView;
@property (nonatomic, retain) NSMutableArray *collectionViewMutableArr;

@end
@implementation RecommendMainViewController
- (void)dealloc
{
    [_tableView release];
    [_elements release];
    [_hotArr release];
    [_dataArr release];
    [_alertView release];
    [_MBprogress release];
    [_cycleScrollView release];
    [_scrollView release];
    [_collectionViewMutableArr release];
    [super dealloc];
}

- (void)viewWillAppear:(BOOL)animated
{
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navigationback.jpg"] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0 / 255.0 green:170.0 / 255.0 blue:205.0 / 255.0 alpha:1.0];
    self.view.backgroundColor = [UIColor colorFromHexCode:@"#F5FFFA"];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], NSForegroundColorAttributeName, nil]];
    // 打开数据库 创建表
    
    DateBaseHandler *dbRec = [DateBaseHandler shareInstance];
    [dbRec openDB];
    [dbRec creataTable];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self handleData];
    // 导航栏的字体和颜色
    [self.navigationController.navigationBar setTitleTextAttributes:
    [NSDictionary dictionaryWithObjectsAndKeys:
    [UIColor whiteColor], NSForegroundColorAttributeName,
    [UIFont fontWithName:@"Arial-Bold" size:0.0], NSFontAttributeName,nil]];
    // 导航栏的颜色
//    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:11.0 / 255 green:199.0 / 255 blue:93.0 / 255 alpha:1];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.bounds.size.height - 64 - 49) style:UITableViewStylePlain];
//    self.tableView.rowHeight = 100;
    // 边框弹动效果
//    self.tableView.bounces = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource  =self;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    [_tableView release];
    
    // 菊花
    self.MBprogress = [[MBProgressHUD alloc] initWithView:self.view];
    self.MBprogress.labelText = @"加载中...";
    self.MBprogress.mode = MBProgressHUDModeIndeterminate;
    [self.view addSubview:self.MBprogress];
    [self.MBprogress show:YES];
    [_MBprogress release];
    
    // 刷新
    [self.tableView addLegendHeaderWithRefreshingBlock:^{
        [self handleData];
    }];
    

    
    // 注册重用池
    [self.tableView registerClass:[ScrollViewCell class] forCellReuseIdentifier:@"scroll"];
    [self.tableView registerClass:[HotCell class] forCellReuseIdentifier:@"hot"];
    [self.tableView registerClass:[FineCell class] forCellReuseIdentifier:@"fine"];
    [self.tableView registerClass:[TopicCell class] forCellReuseIdentifier:@"topic"];
    [self.tableView registerClass:[LineCell class] forCellReuseIdentifier:@"line"];
    
}
// tableView的协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.elements == nil) {
        return 0;
    }
    return 5;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Recommend *recommend = [self.elements objectAtIndex:indexPath.row];
    if (0 == indexPath.row) {
        ScrollViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"scroll"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor colorWithRed:204.0 / 255.0 green:204.0 / 255.0 blue:159.0 / 255.0 alpha:0.8];
        
        cell.cycleScrollView.delegate = self;
        cell.recommend = recommend;
        return cell;
    }else if (1 == indexPath.row){
        HotCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"hot"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        cell.recommend = recommend;
        return cell;
    }else if (2 == indexPath.row){
        FineCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"fine"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        cell.recommend = recommend;
        return cell;
    }else if (3 == indexPath.row){
        TopicCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"topic"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell.topicLabel1 addGestureRecognizer:[self getWebTapGesture2:cell.topicLabel1]];
        cell.topicLabel1.userInteractionEnabled = YES;
        [cell.topicLabel2 addGestureRecognizer:[self getWebTapGesture3:cell.topicLabel2]];
        cell.topicLabel2.userInteractionEnabled = YES;
        cell.recommend = recommend;
        
        return cell;
    }else {
        LineCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"line"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.recommend = recommend;
        [cell.lineLabel addGestureRecognizer:[self getWebTapGesture4:cell.lineLabel]];
        cell.lineLabel.userInteractionEnabled = YES;
        return cell;
    }
}
// cycycleScrollView的代理方法
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    Recommend *recommend = [self.elements firstObject];
    NSArray *arr = [recommend.data firstObject];
    TopicWebViewController *topiVC = [[TopicWebViewController alloc] init];
    topiVC.url = [[arr objectAtIndex:index] objectForKey:@"html_url"];
    [self.navigationController pushViewController:topiVC animated:YES];
    [topiVC release];
}


// 3个webview的点击手势和方法
- (void)webTapAction2:(UITapGestureRecognizer *)tap
{
    UILabel *label = (UILabel *)[self.view viewWithTag:200];
    TopicWebViewController *topiVC = [[TopicWebViewController alloc] init];
    topiVC.url = label.text;
    topiVC.name = @"旅行专题";
    [self.navigationController pushViewController:topiVC animated:YES];
    [self.tableView reloadData];
    [topiVC release];
}

- (UITapGestureRecognizer *)getWebTapGesture2:(UILabel *)text
{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(webTapAction2:)];
    text.tag = 200;
    return [tap autorelease];
}
- (void)webTapAction3:(UITapGestureRecognizer *)tap
{
    UILabel *label = (UILabel *)[self.view viewWithTag:300];
    TopicWebViewController *topiVC = [[TopicWebViewController alloc] init];
    topiVC.url = label.text;
    topiVC.name = @"旅行专题";
    [self.navigationController pushViewController:topiVC animated:YES];
    [self.tableView reloadData];
    [topiVC release];
}

- (UITapGestureRecognizer *)getWebTapGesture3:(UILabel *)text
{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(webTapAction3:)];
    text.tag = 300;
    return [tap autorelease];
}
- (void)webTapAction4:(UITapGestureRecognizer *)tap
{
    UILabel *label = (UILabel *)[self.view viewWithTag:400];
    TopicWebViewController *topiVC = [[TopicWebViewController alloc] init];
    topiVC.url = label.text;
    topiVC.name = @"线下活动";
    [self.navigationController pushViewController:topiVC animated:YES];
    [self.tableView reloadData];
    [topiVC release];
    
}

- (UITapGestureRecognizer *)getWebTapGesture4:(UILabel *)text
{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(webTapAction4:)];
    text.tag = 400;
    return [tap autorelease];
}

// cell的点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (1 == indexPath.row) {
    TrendQueueViewController *trenVC = [[TrendQueueViewController alloc] init];
    trenVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:trenVC animated:YES];
    [trenVC release];
    }
    if (2 == indexPath.row) {
        NiceQueueViewController *niceVC = [[NiceQueueViewController alloc] init];
        niceVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:niceVC animated:YES];
        [niceVC release];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (0 == indexPath.row) {
        return self.view.bounds.size.width / 2;
    }else if (1 == indexPath.row){
        return self.view.bounds.size.width * 2.5 + 30;
    }else if (2 == indexPath.row){
        return self.view.bounds.size.width + 30;
    }else if (3 == indexPath.row){
        return self.view.bounds.size.width * 1.8 + 30;
    }else if (4 == indexPath.row){
        return self.view.bounds.size.width + 30;
    }
    return self.view.bounds.size.width + 30;    
}


// 数据请求

- (void)handleData
{
    NSString *urlStr = @"http://api.breadtrip.com/featured/";
    
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path = [NSString stringWithFormat:@"%@/%ld.happyTripDestination", docPath, [urlStr hash]];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:urlStr parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        BOOL result = [NSKeyedArchiver archiveRootObject:responseObject toFile:path];
        NSLog(@"存储成功: %d", result);
        NSDictionary *array = [responseObject objectForKey:@"elements"];
        
        self.elements = [NSMutableArray array];
        for (NSDictionary *dic in array) {
            if ([[dic objectForKey:@"title"] isEqualToString:@"旅行达人推荐"] == 0) {
                if ([[dic objectForKey:@"title"] isEqualToString:@"每日特价抢购"] == 0) {
                    if ([[dic objectForKey:@"title"] isEqualToString:@"活动专题"] == 0) {
                        Recommend *recommend = [[Recommend alloc] initWithDictionary:dic];
                        [self.elements addObject:recommend];
                        [recommend release];
//                        NSLog(@"recommend: %@", recommend.title);
                    }
                }
            }
        };
        [self.tableView reloadData];
        [self.MBprogress removeFromSuperview];
        // 刷新
        [self.tableView.header endRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        id resultID = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
        self.collectionViewMutableArr = [resultID objectForKey:@"elements"];
        self.elements = [NSMutableArray array];
        for (NSDictionary *dic in self.collectionViewMutableArr) {
            if ([[dic objectForKey:@"title"] isEqualToString:@"旅行达人推荐"] == 0) {
                if ([[dic objectForKey:@"title"] isEqualToString:@"每日特价抢购"] == 0) {
                    if ([[dic objectForKey:@"title"] isEqualToString:@"活动专题"] == 0) {
                        Recommend *recommend = [[Recommend alloc] initWithDictionary:dic];
                        [self.elements addObject:recommend];
                        [recommend release];
                        //                        NSLog(@"recommend: %@", recommend.title);
                    }
                }
            }
        };
        [self.tableView reloadData];

        [self.MBprogress removeFromSuperview];
        self.alertView = [[UIAlertView alloc] initWithTitle:@"网络连接失败,请检查网络" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
        [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(dismissTime) userInfo:nil repeats:NO];
        [self.alertView show];
        [_alertView release];
    }];
//    [self.tableView reloadData];
}
- (void)dismissTime
{
    [self.alertView dismissWithClickedButtonIndex:0.5 animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
